﻿using HealthcareSystem.API.Read.Application.Command.ChronicDisease;
using HealthcareSystem.Domain.ChronicDiseaseManagement;
using MediatR;
using System.Collections.Generic;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel.ChronicDisease
{
    public class HealthEducationShowCommandHandler : IRequestHandler<HealthEducationShowCommand, ApiResult<ApiPaging<List<HealthEducation>>>>
    {
        private readonly IBaseRepository<HealthEducation> heRepository;

        public HealthEducationShowCommandHandler(IBaseRepository<HealthEducation> heRepository)
        {
            this.heRepository = heRepository;
        }

        public Task<ApiResult<ApiPaging<List<HealthEducation>>>> Handle(HealthEducationShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<List<HealthEducation>>> result = new ApiResult<ApiPaging<List<HealthEducation>>>();
            result.Code = ResultCode.查询成功;
            result.Message = ResultCode.查询成功.ToString();

            var list = heRepository.GetAll().Where(x=>x.IsDelete==false);
            if (!string.IsNullOrEmpty(request.MissionContent))
            {
                list = list.Where(x => x.MissionContent.Contains(request.MissionContent));
            }
            var totalCount = list.Count();
            var totalPage = (int)Math.Ceiling((totalCount * 1.0) / request.PageSize);
            list = list.OrderBy(x => x.EducationId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            ApiPaging<List<HealthEducation>> paging = new ApiPaging<List<HealthEducation>>();
            paging.totalPage = totalPage;
            paging.totalCount = totalCount;
            paging.Data = list.ToList();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
